<template>
  <div class="app">
    <div class="add">
      <el-button size="medium" @click="addUser" type="primary" icon="el-icon-circle-plus-outline">添加用户</el-button>
    </div>
    <!-- 用户展示表格 -->
    <el-table :data="tableData.filter(data => !search || data.userName.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%">

        <el-table-column v-for="(item, index) in userAtru" :key="index" :label="item.lable" :prop="item.name">
        </el-table-column>

      <el-table-column align="right">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row), dialogFormVisible = true">Edit</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination :page-size="5" @current-change="getCurrentPage" background layout="prev, pager, next" :total="total">
    </el-pagination>
    <!-- 弹出框 -->
    <el-dialog :title="lableNameForm" :visible.sync="dialogFormVisible" width=30%>
      <el-form :model="ruleFormRegister" :rules="rulesRegister" ref="ruleFormRegister" label-width="100px"
        class="demo-ruleForm">
        <el-form-item label="名字" prop="name">
          <el-input :maxlength="8" v-model="ruleFormRegister.name"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input :maxlength="11" v-model="ruleFormRegister.tel"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input :maxlength="8" show-password type="password" v-model="ruleFormRegister.pass"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleFormRegister.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormRegister('ruleFormRegister')">确认
          </el-button>
          <el-button @click="resetFormRegister('ruleFormRegister')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkphone = (rule, value, callback) => {
      // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    };
    let checkpassword = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,10}$/;
      if (!reg.test(value)) {
        callback(new Error('密码必须是由4-20位字母+数字组合'))
      } else {
        callback()
      }
    }
    return {
      updateId: '',
      userAtru: [
                {
          lable: "ID",
          name: "id"
        },
        {
          lable: "用户名",
          name: "userName"
        },
        {
          lable: "电话号码",
          name: "tel"
        },
        {
          lable: "创建时间",
          name: "createTime"
        },
        {
          lable: "更新时间",
          name: "updateTime"
        },
      ],
      tableData: [],
      search: '',
      page: 0,
      size: 5,
      total: 0,
      isUpdate: false,
      lableNameForm: '更新用户信息',
      //弹出框
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      //更新用户信息
      ruleFormRegister: {
        name: '',
        tel: '',
        pass: '',
        gender: ''
      },
      rulesRegister: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 0, max: 10, message: '长度在 0 到 6 个字符', trigger: 'blur' },
        ],
        tel: [
          { required: true, message: '请输入号码', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        pass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkpassword, trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.getUserList(this.page, this.size);


  },
  mounted() {

  },
  methods: {
    /**
     * 更新用户信息
     * @param {*} index 
     * @param {*} row 
     */
    handleEdit(index, row) {
      this.isUpdate = false;
      this.lableNameForm = "更新用户信息";
      if (!this.isUpdate) {
        this.ruleFormRegister.name = row.userName;
        this.ruleFormRegister.tel = row.tel;
        this.ruleFormRegister.pass = row.passWord;

        this.ruleFormRegister.gender = row.gender;
        this.updateId = row.id;
      }

    },
    /**
     * 删除一条用户
     * @param {*} index 
     * @param {*} row 
     */
    handleDelete(index, row) {
      let userid = localStorage.getItem("userid");
      console.log(userid, row.id)
      if (userid == row.id) {
        this.$message({
          message: '当前用户不可操作',
          type: 'error',
          duration: 1000
        });
        return;
      }
      this.$api.delete({
        id: row.id,
      }).then(res => {
        console.log(res.code)
        if (res.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          });
          this.getUserList(this.page, this.size);
        } else {
          this.$message({
            message: '失败',
            type: 'error',
            duration: 1000
          });
        }

      })

    },
    /**
     * 分页获取用户列表
     * @param {*} page 
     * @param {*} size 
     */
    getUserList(page, size) {
      this.$api.selectList({
        page: page,
        size: size
      }).then(res => {

        // debugger;
        if (res.code === 200) {
          this.tableData = [];
          this.tableData = res.data.records;
          this.total = res.total;

        } else {
          this.$message({
            message: '失败',
            type: 'error',
            duration: 1000
          });
        }

      })
    },

    //提交确认 更新用户信息、添加新用户
    submitFormRegister(formName) {
      if (this.ruleFormRegister.gender === '男') {
        this.ruleFormRegister.gender = 1;

      } else if (this.ruleFormRegister.gender === '女') {
        this.ruleFormRegister.gender = 2;
      } else {
        this.ruleFormRegister.gender = 0;
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          if (this.isUpdate) {

            this.addUserOne();

          } else {
            this.updateInfo();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /**
     * 切换弹框输入为 添加用户信息
     */
    addUser() {
      this.isUpdate = true;
      this.dialogFormVisible = true;
      this.lableNameForm = "添加用户信息";
    },
    resetFormRegister(formName) {
      this.$refs[formName].resetFields();
    },
    getCurrentPage(val) {
      console.log(val);
      this.getUserList(val, this.size);
    },
    updateInfoOne() {
      this.$api.updateInfo({
        id: this.updateId,
        tel: this.ruleFormRegister.tel,
        userName: this.ruleFormRegister.name,
        passWord: this.ruleFormRegister.pass,
        gender: this.ruleFormRegister.gender
      }).then(res => {
        if (res.code === 200) {
          this.getUserList(this.page, this.size);
          this.$message({
            message: '更新成功',
            type: 'success',
            duration: 1000
          });
        } else {
          this.$message({
            message: '更新失败',
            type: 'error',
            duration: 1000
          });
        }


      });


    },
    /**
     * 添加用户网络请求
     */
    addUserOne() {

      this.$api.register({
        tel: this.ruleFormRegister.tel,
        userName: this.ruleFormRegister.name,
        passWord: this.ruleFormRegister.pass,
        gender: this.ruleFormRegister.gender
      }).then(res => {
        if (res.code === 200) {
          this.getUserList(this.page, this.size);
          // this.$message({
          //   message: '更新成功',
          //   type: 'success',
          //   duration: 1000
          // });
        } else if (res.code === 0) {
          this.$message({
            message: '电话号码重复',
            type: 'error',
            duration: 300
          });
        }


      });

    },
        isCellPhone(val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style scoped>
.add {
  margin-top: 20px;
  margin-bottom: 10px;

}
</style>
